var _ = require('underscore');
var cheerio = require('cheerio');
var superagent = require('superagent');
var async = require('async');
var mkdirp = require('mkdirp');
var fs = require('fs');
var http = require('http');

module.exports = function (server) {
  var router = server.loopback.Router();

  //本地存储目录
  var dir = './images';

  //创建目录
  mkdirp(dir, function(err) {
    if(err){
      console.log(err);
    }
  });

  router.get('/easyicon', function (req, res) {

    var url = "http://www.easyicon.net/iconsearch/iconset:flatastic-icons";

    superagent.get(url).end(function (err, sres) {
      if (err) {
        console.log(err)
      }

      var $ = cheerio.load(sres.text);
      var pages_all = $(".pages_all");
      var thisPage = pages_all.find("span");
      var next = thisPage.next();

      var liList = $("#container").find("ol").find("li");
      _.each(liList , function(item  , index){

        if(index == 0 ){
          return;
        }
        var href = $(item).find("a").eq(0).attr("href");
        console.log(href);
        //获取数据，下载
        getHtml(href);
      })

      if(next){

      }

    });

    res.end("1");

  });


  var getHtml = function(href , req){

    var temp = "http://www.easyicon.net" + href;

    superagent.get(temp).end(function (err, sres) {
      if (err) {
        console.log(err)
        return;
      }

      var $ = cheerio.load(sres.text);

      var name = $(".icon_img_one").find("img").attr("alt");
      if(name){
        name = name.replace(/ /g , "_")
      }

      var a96 = $("img[width=96]").parent().find("a").eq(0);
      var href96 = a96.attr("href");

      var a64 = $("img[width=64]").parent().find("a").eq(0);
      var href64 = a64.attr("href");

      var a32 = $("img[width=32]").parent().find("a").eq(0);
      var href32 = a32.attr("href");

      saveImg(href96 , dir , name + "@3x.png" );
      saveImg(href64 , dir , name + "@2x.png" );
      saveImg(href32 , dir , name + ".png" );
    });


  }


  function saveImg(url, dir,name){
    http.get(url, function(res){
      res.setEncoding('binary');
      var data='';
      res.on('data', function(chunk){
        data+=chunk;
      });
      res.on('end', function(){
        fs.writeFile(dir + "/"+name, data, 'binary', function (err) {
          if (err) throw err;
          console.log('file saved '+name);
        });
      });
    }).on('error', function(e) {
      console.log('error'+e)
    });
  }

  server.use(router);
};
